package zheezes.protocol.impl.wt.meta;

import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;

import zheezes.util.AbstractSerial;
import zheezes.util.ArrayUtil;
import zheezes.util.ByteUtil;
import zheezes.util.DateUtil;


public class FrzDate extends AbstractSerial {
	public static final int SIZE = 5;

	private Calendar cal;
	
	public Date getDate() {
		return cal == null ? null : cal.getTime();
	}
	
	public void setDate(Date date) {
		if(cal == null) {
			cal = Calendar.getInstance();
		}
		cal.setTime(date);
		DateUtil.cutoff(cal, Calendar.SECOND, true);
	}

	@Override
	public int getBytes(byte[] buf, int offset) {
		if (cal != null) {
			buf[offset++] = ByteUtil.binToBcd((byte) cal.get(Calendar.MINUTE));
			buf[offset++] = ByteUtil.binToBcd((byte) cal.get(Calendar.HOUR_OF_DAY));
			buf[offset++] = ByteUtil.binToBcd((byte) cal.get(Calendar.DATE));
			buf[offset++] = ByteUtil.binToBcd((byte) (cal.get(Calendar.MONTH) + 1));
			buf[offset++] = ByteUtil.binToBcd((byte) (cal.get(Calendar.YEAR) - 2000));
		} else {
			Arrays.fill(buf, offset, offset + SIZE, (byte) 0xFF);
		}

		return SIZE;
	}

	@Override
	public int setBytes(byte[] buf, int offset, int max) {
		if (ArrayUtil.count(buf, offset, offset + 5, (byte) 0xFF) == 0) {
			if(cal == null) {
				cal = Calendar.getInstance();
				DateUtil.cutoff(cal, Calendar.SECOND, true);
			}
			cal.set(Calendar.MINUTE, ByteUtil.bcdToBin(buf[offset++]));
			cal.set(Calendar.HOUR_OF_DAY, ByteUtil.bcdToBin(buf[offset++]));
			cal.set(Calendar.DATE, ByteUtil.bcdToBin(buf[offset++]));
			cal.set(Calendar.MONTH, ByteUtil.bcdToBin((byte)(buf[offset++] - 1)));
			cal.set(Calendar.YEAR, 2000 + ByteUtil.bcdToBin(buf[offset++]));
		}
		return SIZE;
	}

	@Override
	public int size() {
		return SIZE;
	}
}
